
from init import PATHS
import logging
LOGGER = logging.getLogger(__name__)
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('seaborn')
import seaborn as sns
sns.set(style="white")
pal = sns.color_palette('colorblind')
from C_PatentVariables import conventions_names_colors
dict_subsector_shortnames, dict_var_colors, list_of_subsectors_in_cleancars = conventions_names_colors.main()



def main():
    LOGGER.info('Begin c_othergraphs_policies.py')
    policy_rdd_table()
    plot_OEM_exposure()
    public_chargers()
    LOGGER.info('END c_othergraphs_policies.py')


def policy_strategies_summary():
    df_table = pd.read_excel(PATHS.rawdata / 'PolicyLandscaping/clean_strategy_table_forSOM.xlsx',sheet_name= 'so_byperiod')
    df_table = df_table.fillna('')
    df_table = df_table.set_index(['Country', 'Period'])
    df_table_tex = df_table.to_latex(index = True, column_format="ccC{7cm}C{2cm}", multirow=True)
    with open(PATHS.tables /  'clean_strategy_table_forSOM2.tex', "w") as f:
        f.write(df_table_tex)


def policy_strategies_countrytables():
    df_table = pd.read_excel(PATHS.rawdata / 'PolicyLandscaping/clean_strategy_table_forSOM.xlsx',sheet_name= 'policy_by_policy')
    df_table['Country'] = df_table['Country'].fillna(method='ffill')
    df_table = df_table.fillna('')
    df_table['Evidence from the document'] = df_table['Evidence from the document'].apply(lambda x: '\\tiny ' + x)
    df_table['Evidence from the document'] = df_table['Evidence from the document'].apply(lambda x: x.replace('&','\&'))
    for country in ['Japan','China','South Korea','France','UK','Germany','USA']:
        df_country = df_table.loc[df_table['Country']==country]
        df_country = df_country.drop('Country',axis=1)
        df_table_tex = df_country.to_latex(index=False, column_format="C{3cm}C{1.5cm}C{2cm}C{1.5cm}C{1.5cm}C{2cm}L{10cm}", multirow=True)
        df_table_tex = df_table_tex.split('\\\\\n')[1:-1]# skip preamble and end
        df_table_tex  = [text.replace('\n',' ') for text in df_table_tex]
        df_table_tex = ['\\hline ' + text if text.split('&')[0].strip() != '' else text for text in df_table_tex]
        preamble = """\\textbf{Policy name} & \\textbf{Period} & \\textbf{Government body}& 
        \\textbf{Primary technology} & \\textbf{Secondary technology}& \\textbf{Reference} & 
        \\textbf{Evidence from the document} \\\\ \\hline 
        \\endfirsthead \n
        \\\\
        \\multicolumn{3}{c}%
        {{\\bfseries \\tablename\\ \\thetable{} -- continued from previous page}} \\\\
        \\hline \\textbf{Policy name} & \\textbf{Period} & \\textbf{Government body}& 
        \\textbf{Primary technology} & \\textbf{Secondary technology}& \\textbf{Reference} & 
        \\textbf{Evidence from the document} \\\\ \\hline  
        \\endhead \n
        \\\\
        \\hline \\multicolumn{3}{|r|}{{Continued on next page}} \\\\ \\hline
        \\endfoot \n

        \\hline \\hline
        \\endlastfoot \n
        """
        df_table_tex = preamble + '\\\\\n'.join(df_table_tex)
        with open(PATHS.tables /  'SO_{}_forSOM.tex'.format(country), "w") as f:
            f.write(df_table_tex)


def policy_rdd_table():
    df_table = pd.read_excel(PATHS.rawdata / 'PolicyLandscaping/RDDfunding_table_forSOM.xlsx')
    df_table = df_table.fillna('')
    df_table = df_table.set_index(['Country', 'Period'])
    df_table_tex = df_table.to_latex(index=True, column_format="cccc", multirow=True)
    with open(PATHS.tables / 'rddfunding_table_forSOM.tex', "w") as f:
        f.write(df_table_tex)


def plot_OEM_exposure():
    dffirmyear_policy = pd.read_csv(PATHS.dropbox / 'Data_outputted/D_Policy/firm_year_policy_exposure.csv')
    OEMs = pd.read_csv(PATHS.dropbox / 'Data_outputted/A_AutoIndustry/OEMs_shortenednamesforgraphs.csv')
    dffirmyear_policy = dffirmyear_policy.merge(OEMs[['OEM_Level1_ID', 'shortname']].drop_duplicates(), on='OEM_Level1_ID')
    dffirmyear_policy = dffirmyear_policy[dffirmyear_policy['Year'] <= 2019]
    fig, ax = plt.subplots()
    ax.plot(dffirmyear_policy.groupby('Year')['otherstorage_RDexposure'].mean(), label='RD&D Battery and Other Storage', color=dict_var_colors['Count_Bat'][1], linewidth=3)
    ax.plot(dffirmyear_policy.groupby('Year')['fchydrogen_RDexposure'].mean(), label='RD&D Fuel Cell', color=dict_var_colors['Count_FC'][1], linewidth=3)
    ax.set(ylabel='Mean RD&D Exposure (2018 Million USD)', xlabel='Years')
    ax2 = ax.twinx()
    ax2.plot(dffirmyear_policy.groupby('Year')['strat_bev_exposure'].mean(), label='Strategy Battery', color=dict_var_colors['Count_Bat'][1], linewidth=2, linestyle='--')
    ax2.plot(dffirmyear_policy.groupby('Year')['strat_fc_exposure'].mean(), label='Strategy Fuel Cell', color=dict_var_colors['Count_FC'][1], linewidth=2, linestyle='--')
    # ax2.set(ylabel='Mean Strategic Focus Exposure', xlabel='Years', fontsize=10)
    ax2.set(ylabel='Mean Strategic Focus Exposure', xlabel='Years')
    h1, l1 = ax.get_legend_handles_labels()
    h2, l2 = ax2.get_legend_handles_labels()
    ax.legend(h1 + h2, l1 + l2, loc="best", ncol=1, frameon=False)
    fig.savefig(PATHS.figures / f'policies/OEM_policy_exposure.png', bbox_inches='tight')
    fig.savefig(PATHS.figures / f'policies/OEM_policy_exposure.pdf', bbox_inches='tight')
    plt.close()
    return


def public_chargers():
    public_chargers = pd.read_csv(PATHS.dropbox / 'Data_outputted/D_Policy/public_charging_stations_by_year_by_country.csv')
    for country in public_chargers['Country'].unique():
        plt.plot(public_chargers[public_chargers['Country']==country]['Year'].values, public_chargers[public_chargers['Country']==country]['Public_chargers'].values,label = country)
    plt.yscale('log')
    plt.xlabel('Year')
    plt.ylabel('Number of public chargers (log)')
    plt.legend(ncol=1)
    plt.savefig(PATHS.figures / 'policies' / 'public_chargers.pdf',bbox_inches = 'tight')
    plt.savefig(PATHS.figures / 'policies' / 'public_chargers.png',bbox_inches = 'tight')
    plt.close()
